package com.buer.storage.controller;

import com.buer.storage.dto.ProdDto;
import com.buer.storage.dto.PutStorageDto;
import com.buer.storage.dto.WorderExcelDto;
import com.buer.storage.entity.*;
import com.buer.storage.service.*;
import com.buer.storage.utils.*;
import com.buer.storage.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2021/1/28.
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private ProdCategoryService prodCategoryService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ProdService prodService;

    @Autowired
    private CategoryTwoService categoryTwoService;

    @Autowired
    private WorderService worderService;

    @Autowired
    private WorderdetailsService worderdetailsService;

    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/getTemplate")
    public R getTemplate() {
        String[] handers = {"序号", "装备大类", "装备细类", "装备名称", "数量", "单位", "采购单价", "规格型号", "供应商名称", "库区", "库位", "到期时间"}; //列标题
       /* Map<String, List<String>> data = new HashMap<>();
        data.put("灭火类消防车", Arrays.asList("供水消防车（GS）", "水罐消防车（SG）", "泡沫消防车（PM）"));
        data.put("举高类消防车", Arrays.asList("登高平台消防车（DG）", "云梯消防车（YT）", "云梯消防车（YT）"));*/
        Map<String, List<String>> dataProdCate = new HashMap<>();
        List<ProdCategory> select = prodCategoryService.select();
        for (ProdCategory category : select) {
            List<String> childName = prodCategoryService.getChildName(category.getCategoryId());
            if (childName != null && childName.size() > 0) {
                dataProdCate.put(category.getCategoryName(), childName);
            }
        }

        Map<String, List<String>> dataArea = new HashMap<>();
        List<Area> areaList = areaService.getAll();
        for (Area area : areaList) {
            List<String> departmentList = areaService.getDepartmentByAreaId(area.getAreaId());
            if (departmentList != null && departmentList.size() > 0) {
                dataArea.put(area.getAreaName() + "_" + area.getAreaNumber(), departmentList);
            }
        }

        //查询所有供应商
        List<String> supplier = supplierService.getAllSupplier();
        if (supplier == null) {
            supplier = new ArrayList<>();
        }

        byte[] excelTemplate = ExcelUtil.createExcelTemplate(handers, dataProdCate, dataArea, supplier);

        String url = OssUtil.upload("批量新增模板.xls", excelTemplate);

        return R.ok(url);
    }

    @PostMapping("/upload")
    @Transactional
    public R upload(MultipartFile file) {
        String fileName = file.getOriginalFilename();

        ExcelReader reader = null;
        List<String> errorMessageList = new ArrayList<String>();
        try {
            if (fileName.endsWith(".xls") || fileName.endsWith(".XLS")) {
                reader = new ExcelReader(file.getInputStream(), ExcelReader.ExcelType.Excel_2003);
            } else {
                reader = new ExcelReader(file.getInputStream(), ExcelReader.ExcelType.Excel_2007);
            }
            List<WorderExcelDto> worderExcelList = (List<WorderExcelDto>) reader.readList(WorderExcelDto.class, errorMessageList);

            if(CheckEmptyUtil.isNotEmpty(errorMessageList)){
                return R.setR(0, "失败", errorMessageList);
            }

            Map<String, Object> prodMap = new HashMap<>();
            Map<String, Object> categoryTwoMap = new HashMap<>();


            if (CheckEmptyUtil.isNotEmpty(worderExcelList)) {
                //1、保存入库订单表
                String worderOrderNum= CommonGeneratorUtil.generatorWorderOrderNum();
                PutStorageDto putStorageDto = new PutStorageDto();

                putStorageDto.setOrderNum(worderOrderNum);
                putStorageDto.setPutDate(DateUtil.getCurrDate());
                putStorageDto.setPutTypeid(1);
                putStorageDto.setPutStatus(2);
                worderService.save(putStorageDto);

                for (WorderExcelDto worderExcelDto : worderExcelList) {
                    //2、查询是否有此装备
                    prodMap.put("prodName", worderExcelDto.getEquipmentName());
                    prodMap.put("prodSpecial", worderExcelDto.getSpecification());
                    String prodCode = null;
                    ProdDto prodByNameAndSpecial = prodService.getProdByNameAndSpecial(prodMap);
                    if (prodByNameAndSpecial == null) {
                        //没有此装备，往装备表中加入装备
                        prodByNameAndSpecial = new ProdDto();
                        prodByNameAndSpecial.setProdName(worderExcelDto.getEquipmentName());
                        //生产Code
                        prodCode = getProdCode();
                        prodByNameAndSpecial.setProdCode(prodCode);
                        prodByNameAndSpecial.setProdSpecial(worderExcelDto.getSpecification());
                        prodByNameAndSpecial.setPrice(new BigDecimal(worderExcelDto.getPrice()));
                        prodByNameAndSpecial.setEmit(worderExcelDto.getEmit());
                        Supplier supplierByName = supplierService.getSupplierByName(worderExcelDto.getSupplier());
                        prodByNameAndSpecial.setSupplierId(supplierByName.getSupplierId());
                        categoryTwoMap.put("categoryName", worderExcelDto.getBigEquipment());
                        categoryTwoMap.put("categoryTwoName", worderExcelDto.getSmallEquipment());
                        CarCategorytwo categorytwoByName = categoryTwoService.getCategorytwoByName(categoryTwoMap);
                        prodByNameAndSpecial.setCategoryTwoId(categorytwoByName.getCategoryTwoId());
                        //保存装备
                        prodService.save(prodByNameAndSpecial);
                    } else {
                        prodCode = prodByNameAndSpecial.getProdCode();
                    }
                    //3、保存入库订单详情
                    WorderdetailsDO worderdetailsDO=new WorderdetailsDO();
                    worderdetailsDO.setProdCode(prodCode);
                    worderdetailsDO.setProdName(worderExcelDto.getEquipmentName());
                    worderdetailsDO.setProdSpecial(worderExcelDto.getSpecification());
                    worderdetailsDO.setProdBatch(CommonGeneratorUtil.generatorWorderOrderDetailBatchNo());
                    worderdetailsDO.setProdNum(worderExcelDto.getNum());
                    worderdetailsDO.setProdPrice(new BigDecimal(worderExcelDto.getPrice()));
                    worderdetailsDO.setEmit(worderExcelDto.getEmit());
                    worderdetailsDO.setSupplierId(prodByNameAndSpecial.getSupplierId());

                    //库区
                    String area = worderExcelDto.getArea().split("_")[0];
                    Area areaByName = areaService.getAreaByName(area);
                    worderdetailsDO.setProdArea(areaByName.getAreaId());
                    //库位
                    String location = worderExcelDto.getLocation();
                    Department departmentByName = departmentService.getDepartmentByName(location);
                    worderdetailsDO.setProdDepart(departmentByName.getDepartmentId());
                    worderdetailsDO.setProdDate(worderExcelDto.getExpireDate());
                    worderdetailsDO.setWorderPutid(putStorageDto.getPutId());
                    worderdetailsDO.setCategoryTwoId(prodByNameAndSpecial.getCategoryTwoId());
                    worderdetailsService.save(worderdetailsDO);

                }

                return R.setR(1, "成功", null);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return R.setR(0, "失败", null);
        }


        return R.setR(0, "失败", null);
    }


    public String getProdCode() {
        String prodCode = CommonGeneratorUtil.generatorProdCode();
        ProdDto prodByCode = prodService.getProdByCode(prodCode);
        if (prodByCode != null) {
            return getProdCode();
        } else {
            return prodCode;
        }

    }

}
